﻿using Admin.CommonLib.Constants;
using Admin.CommonLib.Models.Role;
using Admin.CommonLib.Models.User;
using Newtonsoft.Json;
using Swimj.CommonLib.Base;
using Swimj.Core.Extensions;
using System.Net.Http.Json;

namespace Admin.RazorLib.Services
{
    public class RoleService : IRoleService
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public RoleService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<PaginatedResult<RoleInfoResponseDto>> QueryRolesByPage(RoleSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync(model.ToQueryString(ApiRoutes.Role.QueryRoles));
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<PaginatedResult<RoleInfoResponseDto>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<List<RoleInfoResponseDto>>> QueryRoles(RoleSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.Role.QueryRoles}");
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<List<RoleInfoResponseDto>>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<RoleInfoResponseDto>> CreateRole(RoleEditRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.PostAsJsonAsync($"/{ApiRoutes.Role.CreateRole}", model);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<RoleInfoResponseDto>>(resultJson);
                    }
                }

                return new Result<RoleInfoResponseDto>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<RoleInfoResponseDto>> UpdateRole(Guid key, RoleEditRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.PutAsJsonAsync($"/{ApiRoutes.Role.UpdateRole.Replace("{id}", key.ToString())}", model);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<RoleInfoResponseDto>>(resultJson);
                    }
                }

                return new Result<RoleInfoResponseDto>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<RoleInfoResponseDto>> GetRole(Guid key)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.Role.GetRole.Replace("{id}", key.ToString())}");
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<RoleInfoResponseDto>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<HttpResponseMessage> ExportRoles(RoleSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.Role.ExportRole}");
                return response;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<HttpResponseMessage> ExportTemplate()
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.Role.ExportTemplateRole}");
                return response;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<IList<RoleClaimResponseDto>>> QueryPermissionsByRole(Guid key)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.Role.QueryPermissions.Replace("{id}", key.ToString())}");
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<IList<RoleClaimResponseDto>>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<IList<RoleClaimResponseDto>>> UpdatePermissionsByRole(Guid key, List<string> model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.PutAsJsonAsync($"/{ApiRoutes.Role.UpdatePermissions.Replace("{id}", key.ToString())}", model);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<IList<RoleClaimResponseDto>>>(resultJson);
                    }
                }

                return new Result<IList<RoleClaimResponseDto>>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<PaginatedResult<UserInfoResponseDto>> QueryUsersByRole(Guid key, UserSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.GetAsync($"/{ApiRoutes.Role.QueryUsers.Replace("{id}", key.ToString())}");
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<PaginatedResult<UserInfoResponseDto>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<IList<UserInfoResponseDto>>> UpdateUsersByRole(Guid key, RoleOperateRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");
                var response = await httpClient.PutAsJsonAsync($"/{ApiRoutes.Role.UpdateUsers.Replace("{id}", key.ToString())}", model);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<IList<UserInfoResponseDto>>>(resultJson);
                    }
                }

                return new Result<IList<UserInfoResponseDto>>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<IList<RoleImportResponseDto>>> ImportRoles(int importType, string fileName, Stream stream)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("adminApi");

                var multipartFormDataContent = new MultipartFormDataContent();
                multipartFormDataContent.Add(new StreamContent(stream), "file", fileName);
                var response =
                    await httpClient.PostAsync($"/{ApiRoutes.Role.ImportRole}?importType={importType}",
                        multipartFormDataContent);

                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<IList<RoleImportResponseDto>>>(resultJson);
                    }
                }

                return new Result<IList<RoleImportResponseDto>>();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}